<template>
  <div class="main">
    <div class="left">
      <el-card shadow="hover" class="card-box">
        <div class="card-header">
          <span>奖学金管理</span>
        </div>
        <div class="menu-list">
          <div
              v-for="menu in menus"
              :key="menu.name"
              :class="{ 'menu-item': true, 'active': selectedMenu === menu.name }"
              @click="selectMenu(menu)"
          >
            <i :class="menu.icon"></i>
            <span>{{ menu.name }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <div class="right">
      <!-- 首页内容 -->
      <div class="content" v-if="selectedMenu === '首页'">
        <div class="content-header">
          <h2>奖学金管理系统</h2>
          <p style="color: #666; margin-top: 10px;">
            所有学生自动参加奖学金评选，无需手动申请。系统将根据各项成绩自动计算排名。
          </p>
        </div>
        <div class="dashboard">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.totalScore }}</div>
                  <div class="stat-label">总分</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.academicScore }}</div>
                  <div class="stat-label">学业成绩</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.politicalScore }}</div>
                  <div class="stat-label">思政成绩</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.sciScore }}</div>
                  <div class="stat-label">科研成绩</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.serviceScore }}</div>
                  <div class="stat-label">社会服务</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.competitionScore }}</div>
                  <div class="stat-label">学科竞赛</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.paperScore }}</div>
                  <div class="stat-label">学术论文</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.ipScore }}</div>
                  <div class="stat-label">知识产权</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 奖学金查询内容 -->
      <div class="content" v-if="selectedMenu === '奖学金查询'">
        <div class="content-header">
          <h2>奖学金查询</h2>
          <p style="color: #666; margin-top: 10px;">
            查询奖学金排名情况，所有学生自动参与评选
          </p>
          <div>
            <el-button type="success" @click="queryMyRanking">查询我的排名</el-button>
            <el-button type="primary" @click="manualRefresh" :loading="loading">
              <el-icon><Refresh /></el-icon>
              手动刷新
            </el-button>
            <el-button
                :type="autoRefreshEnabled ? 'warning' : 'info'"
                @click="toggleAutoRefresh"
            >
              <el-icon><Timer /></el-icon>
              {{ autoRefreshEnabled ? '关闭自动刷新' : '开启自动刷新' }}
            </el-button>
            <el-tag v-if="autoRefreshEnabled" type="success" style="margin-left: 10px;">
              自动刷新已开启 ({{ refreshInterval / 1000 }}秒)
            </el-tag>
          </div>
        </div>

        <!-- 个人排名信息 -->
        <div class="ranking-info" v-if="myRanking">
          <el-card style="margin-bottom: 20px;">
            <template #header>
              <span>我的排名信息</span>
            </template>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="奖学金类型">
                <el-tag v-if="myRanking.scholarshipType" type="success">{{ myRanking.scholarshipType }}</el-tag>
                <el-tag v-else type="info">未设置</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="评选学年">
                <el-tag type="info">{{ formatAcademicYear(myRanking.applicationYear) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="总分">
                <span style="font-weight: bold; color: #409eff;">{{ myRanking.totalScore || 0 }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="排名">
                <span v-if="myRanking.ranking" style="color: #e6a23c; font-weight: bold;">第{{ myRanking.ranking }}名</span>
                <span v-else style="color: #999;">未排名</span>
              </el-descriptions-item>
              <el-descriptions-item label="最终结果">
                <el-tag :type="myRanking.finalResult === '获奖' ? 'success' : 'info'">
                  {{ myRanking.finalResult || '待公布' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="是否符合条件">
                <el-tag :type="myRanking.isQualified ? 'success' : 'danger'">
                  {{ myRanking.isQualified ? '符合' : '不符合' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <!-- 排名列表 -->
        <div class="ranking-list">
          <el-card>
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>奖学金排名列表</span>
                <div>
                  <el-select v-model="selectedGrade" placeholder="选择年级" style="width: 120px; margin-right: 10px;">
                    <el-option label="研二" :value="2"></el-option>
                    <el-option label="研三" :value="3"></el-option>
                  </el-select>
                  <el-select v-model="selectedScholarshipType" placeholder="奖学金类型" style="width: 150px; margin-right: 10px;">
                    <el-option label="国家奖学金" value="国家奖学金"></el-option>
                    <el-option label="学业奖学金" value="学业奖学金"></el-option>
                    <el-option label="专项奖学金" value="专项奖学金"></el-option>
                  </el-select>
                  <el-button type="primary" @click="loadRankingData">查询排名</el-button>
                </div>
              </div>
            </template>

            <el-table :data="pagedRankingList" v-loading="loading" style="width: 100%">
              <el-table-column prop="ranking" label="排名" width="80" align="center">
                <template #default="scope">
                  <span v-if="scope.row.ranking" style="font-weight: bold; color: #e6a23c;">
                    第{{ scope.row.ranking }}名
                  </span>
                  <span v-else style="color: #999;">未排名</span>
                </template>
              </el-table-column>
              <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
              <el-table-column prop="name" label="姓名" width="100"></el-table-column>
              <el-table-column prop="scholarshipType" label="奖学金类型" width="120">
                <template #default="scope">
                  <el-tag v-if="scope.row.scholarshipType" type="success">{{ scope.row.scholarshipType }}</el-tag>
                  <el-tag v-else type="info">未设置</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="applicationYear" label="评选学年" width="100">
                <template #default="scope">
                  {{ formatAcademicYear(scope.row.applicationYear) }}
                </template>
              </el-table-column>
              <el-table-column prop="totalScore" label="总分" width="100" align="center">
                <template #default="scope">
                  <span style="font-weight: bold; color: #409eff;">{{ scope.row.totalScore || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="finalResult" label="最终结果" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.finalResult === '获奖' ? 'success' : 'info'">
                    {{ scope.row.finalResult || '待公布' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="isQualified" label="是否符合条件" width="120" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.isQualified ? 'success' : 'danger'">
                    {{ scope.row.isQualified ? '符合' : '不符合' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewCandidateDetail(scope.row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                :current-page="rankingPage.value"
                :page-size="rankingPageSize.value"
                :total="Array.isArray(rankingList?.value) ? rankingList.value.length : 0"
                layout="prev, pager, next"
                @current-change="handleRankingPageChange"
                style="margin-top: 16px; text-align: right;"/>
          </el-card>
        </div>
      </div>

      <!-- 候选查询内容 -->
      <div class="content" v-if="selectedMenu === '候选查询'">
        <div class="content-header">
          <h2>候选查询</h2>
          <p style="color: #666; margin-top: 10px;">
            查看所有参与奖学金评选的学生名单
          </p>
          <div>
            <el-button type="success" @click="queryMyRanking">查询我的排名</el-button>
            <el-input
                v-model="candidateSearchKeyword"
                placeholder="搜索学号或姓名"
                style="width: 200px; margin-right: 10px;"
                clearable
                @input="filterCandidates"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
                v-model="candidateFilterType"
                placeholder="奖学金类型"
                style="width: 150px; margin-right: 10px;"
                clearable
                @change="filterCandidates"
            >
              <el-option label="国家奖学金" value="国家奖学金"></el-option>
              <el-option label="学业奖学金" value="学业奖学金"></el-option>
              <el-option label="专项奖学金" value="专项奖学金"></el-option>
            </el-select>
            <el-button type="primary" @click="manualRefresh" :loading="loading">
              <el-icon><Refresh /></el-icon>
              手动刷新
            </el-button>
            <el-button
                :type="autoRefreshEnabled ? 'warning' : 'info'"
                @click="toggleAutoRefresh"
            >
              <el-icon><Timer /></el-icon>
              {{ autoRefreshEnabled ? '关闭自动刷新' : '开启自动刷新' }}
            </el-button>
            <el-tag v-if="autoRefreshEnabled" type="success" style="margin-left: 10px;">
              自动刷新已开启 ({{ refreshInterval / 1000 }}秒)
            </el-tag>
          </div>
        </div>

        <!-- 个人排名信息 -->
        <div class="ranking-info" v-if="myRanking">
          <el-card style="margin-bottom: 20px;">
            <template #header>
              <span>我的排名信息</span>
            </template>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="奖学金类型">
                <el-tag v-if="myRanking.scholarshipType" type="success">{{ myRanking.scholarshipType }}</el-tag>
                <el-tag v-else type="info">未设置</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="评选学年">
                <el-tag type="info">{{ formatAcademicYear(myRanking.applicationYear) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="总分">
                <span style="font-weight: bold; color: #409eff;">{{ myRanking.totalScore || 0 }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="排名">
                <span v-if="myRanking.ranking" style="color: #e6a23c; font-weight: bold;">第{{ myRanking.ranking }}名</span>
                <span v-else style="color: #999;">未排名</span>
              </el-descriptions-item>
              <el-descriptions-item label="最终结果">
                <el-tag :type="myRanking.finalResult === '获奖' ? 'success' : 'info'">
                  {{ myRanking.finalResult || '待公布' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="是否符合条件">
                <el-tag :type="myRanking.isQualified ? 'success' : 'danger'">
                  {{ myRanking.isQualified ? '符合' : '不符合' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <div class="candidate-list">
          <el-card>
            <template #header>
              <span>参与评选学生列表</span>
            </template>
            <el-table :data="pagedCandidateList" v-loading="loading" style="width: 100%">
              <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
              <el-table-column prop="name" label="姓名" width="100"></el-table-column>
              <el-table-column prop="scholarshipType" label="奖学金类型" width="120">
                <template #default="scope">
                  <el-tag v-if="scope.row.scholarshipType" type="success">{{ scope.row.scholarshipType }}</el-tag>
                  <el-tag v-else type="info">未设置</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="applicationYear" label="评选学年" width="100">
                <template #default="scope">
                  {{ formatAcademicYear(scope.row.applicationYear) }}
                </template>
              </el-table-column>
              <el-table-column prop="totalScore" label="总分" width="100" align="center">
                <template #default="scope">
                  <span style="font-weight: bold; color: #409eff;">{{ scope.row.totalScore || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="ranking" label="排名" width="100" align="center">
                <template #default="scope">
                  <span v-if="scope.row.ranking" style="color: #e6a23c; font-weight: bold;">第{{ scope.row.ranking }}名</span>
                  <span v-else style="color: #999;">未排名</span>
                </template>
              </el-table-column>
              <el-table-column prop="finalResult" label="最终结果" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.finalResult === '获奖' ? 'success' : 'info'">
                    {{ scope.row.finalResult || '待公布' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="isQualified" label="是否符合条件" width="120" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.isQualified ? 'success' : 'danger'">
                    {{ scope.row.isQualified ? '符合' : '不符合' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewCandidateDetail(scope.row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                :current-page="candidatePage.value"
                :page-size="candidatePageSize.value"
                :total="Array.isArray(filteredCandidateList?.value) ? filteredCandidateList.value.length : 0"
                layout="prev, pager, next"
                @current-change="handleCandidatePageChange"
                style="margin-top: 16px; text-align: right;"/>
          </el-card>
        </div>
      </div>
      <!-- 学科竞赛内容 -->
      <div class="content" v-if="selectedMenu === '学科竞赛'">
        <div class="content-header">
          <h2>学科竞赛管理</h2>
          <el-button type="primary" @click="showCompetitionDialog">新建申请</el-button>
        </div>
        <div class="competition-list">
          <el-table :data="competitionList" v-loading="loading" stripe>
            <el-table-column prop="competitionName" label="竞赛名称" width="200"></el-table-column>
            <el-table-column prop="awardLevel" label="获奖等级" width="120"></el-table-column>
            <el-table-column prop="score" label="得分" width="100"></el-table-column>
            <el-table-column prop="academicYear" label="学年" width="120"></el-table-column>
            <el-table-column prop="reviewStatus" label="审核状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.reviewStatus)">
                  {{ getStatusText(scope.row.reviewStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editCompetition(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCompetition(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 学术论文内容 -->
      <div class="content" v-if="selectedMenu === '学术论文'">
        <div class="content-header">
          <h2>学术论文管理</h2>
          <el-button type="primary" @click="showPaperDialog">新建申请</el-button>
        </div>
        <div class="paper-list">
          <el-table :data="paperList" v-loading="loading" stripe>
            <el-table-column prop="paperTitle" label="论文标题" width="250"></el-table-column>
            <el-table-column prop="paperType" label="论文类型" width="120"></el-table-column>
            <el-table-column prop="contributionRank" label="贡献排名" width="100"></el-table-column>
            <el-table-column prop="score" label="得分" width="100"></el-table-column>
            <el-table-column prop="academicYear" label="学年" width="120"></el-table-column>
            <el-table-column prop="reviewStatus" label="审核状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.reviewStatus)">
                  {{ getStatusText(scope.row.reviewStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editPaper(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deletePaper(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 知识产权内容 -->
      <div class="content" v-if="selectedMenu === '知识产权'">
        <div class="content-header">
          <h2>知识产权管理</h2>
          <el-button type="primary" @click="showIpDialog">新建申请</el-button>
        </div>
        <div class="ip-list">
          <el-table :data="ipList" v-loading="loading" stripe>
            <el-table-column prop="name" label="知识产权名称" width="200"></el-table-column>
            <el-table-column prop="ipType" label="类型" width="120"></el-table-column>
            <el-table-column prop="ipStatus" label="状态" width="120"></el-table-column>
            <el-table-column prop="score" label="得分" width="100"></el-table-column>
            <el-table-column prop="academicYear" label="学年" width="120"></el-table-column>
            <el-table-column prop="reviewStatus" label="审核状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.reviewStatus)">
                  {{ getStatusText(scope.row.reviewStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editIp(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteIp(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 社会服务内容 -->
      <div class="content" v-if="selectedMenu === '社会服务'">
        <div class="content-header">
          <h2>社会服务填报表管理</h2>
          <el-button type="primary" @click="showSocialServiceDialog">新建申请</el-button>
        </div>
        <div class="social-service-list">
          <el-table :data="socialServiceList" v-loading="loading" stripe>
            <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
            <el-table-column prop="serviceType" label="服务类型" width="150"></el-table-column>
            <el-table-column prop="activityName" label="服务名称" width="200"></el-table-column>
            <el-table-column prop="academicYear" label="学年" width="120"></el-table-column>
            <el-table-column prop="startDate" label="开始时间" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.startDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="结束时间" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.endDate) }}
              </template>
            </el-table-column>
            <el-table-column label="时长" width="100">
              <template #default="scope">
                {{ calculateDuration(scope.row.startDate, scope.row.endDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="editSocialService(scope.row)">
                  <el-icon><Document /></el-icon>编辑
                </el-button>
                <el-button size="small" type="info" @click="viewProof(scope.row)">
                  <el-icon><ZoomIn /></el-icon>查看证明
                </el-button>
                <el-button size="small" type="danger" @click="deleteSocialService(scope.row.id)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 思政成绩内容 -->
      <div class="content" v-if="selectedMenu === '思政成绩'">
        <div class="content-header">
          <h2>思政成绩管理</h2>
        </div>
        <div class="political-score">
          <el-card>
            <template #header>
              <span>思政表现评分</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="学号">{{ currentUser?.userId }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ currentUser?.username }}</el-descriptions-item>
              <el-descriptions-item label="基础分">{{ politicalScore.baseScore || 0 }}</el-descriptions-item>
              <el-descriptions-item label="荣誉加分">{{ politicalScore.honorScore || 0 }}</el-descriptions-item>
              <el-descriptions-item label="导师组评价分">{{ politicalScore.advisorScore || 0 }}</el-descriptions-item>
              <el-descriptions-item label="扣分">{{ politicalScore.deduction || 0 }}</el-descriptions-item>
              <el-descriptions-item label="总分" :span="2">
                <span class="total-score">{{ politicalScore.totalScore || 0 }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </div>

      <!-- 通知公告内容 -->
      <div class="content" v-if="selectedMenu === '通知公告'">
        <div class="content-header">
          <h2>通知公告</h2>
        </div>
        <div class="notice-list">
          <el-card>
            <template #header>
              <span>最新通知</span>
            </template>
            <el-timeline>
              <el-timeline-item
                  v-for="notice in notices"
                  :key="notice.id"
                  :timestamp="notice.date"
                  placement="top"
              >
                <el-card>
                  <h4>{{ notice.title }}</h4>
                  <p>{{ notice.content }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 社会服务申请对话框 -->
    <el-dialog
        v-model="socialServiceDialogVisible"
        title="社会服务申请"
        width="60%"
        :before-close="handleCloseDialog"
    >
      <el-form
          ref="socialServiceFormRef"
          :model="socialServiceForm"
          :rules="socialServiceFormRules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="socialServiceForm.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="socialServiceForm.studentId" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务类型" prop="service_type">
              <el-select
                  v-model="socialServiceForm.service_type"
                  placeholder="请选择服务类型"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="rule in socialServiceRules"
                    :key="rule.ruleKey"
                    :label="`${rule.ruleName} (${rule.scoreValue}分)`"
                    :value="rule.ruleKey"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ rule.ruleName }}</span>
                    <span style="color: #409eff; font-weight: bold;">{{ rule.scoreValue }}分</span>
                  </div>
                  <div style="font-size: 12px; color: #999; margin-top: 4px;">
                    {{ rule.description }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学年" prop="academic_year">
              <el-select
                  v-model="socialServiceForm.academic_year"
                  placeholder="请选择学年"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="year in academicYearList"
                    :key="year.value"
                    :label="year.label"
                    :value="year.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 服务类型详细信息提示 -->
        <el-row v-if="selectedServiceRule">
          <el-col :span="24">
            <el-alert
                :title="`${selectedServiceRule.ruleName} - 评分规则`"
                :description="`${selectedServiceRule.description} | 基础分数：${selectedServiceRule.scoreValue}分${selectedServiceRule.maxTimes ? ` | 最大次数：${selectedServiceRule.maxTimes}次` : ''}`"
                type="info"
                :closable="false"
                show-icon
                style="margin-bottom: 20px;"
            />
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="isPositionType ? '担任职务' : '活动名称'" prop="activity_name">
              <el-input
                  v-model="socialServiceForm.activity_name"
                  :placeholder="isPositionType ? '请输入担任的职务名称' : '请输入活动名称'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务日期" prop="service_date">
          <el-date-picker
              v-model="socialServiceForm.service_date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="服务描述" prop="description">
          <el-input
              v-model="socialServiceForm.description"
              type="textarea"
              :rows="4"
              placeholder="请详细描述服务内容、您的具体工作以及取得的成果"
              show-word-limit
              maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item label="证明材料" prop="proof">
          <el-upload
              action="#"
              :auto-upload="false"
              :limit="3"
              :on-change="handleProofUpload"
              :on-remove="handleProofRemove"
              :file-list="socialServiceForm.proof_files"
              list-type="picture-card"
              :before-upload="beforeProofUpload"
              multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
        </el-row>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="socialServiceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitSocialServiceForm" :loading="submitting">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewImageUrl" style="width: 100%" />
    </el-dialog>

    <!-- 学科竞赛对话框 -->
    <el-dialog
        v-model="competitionDialogVisible"
        title="学科竞赛申请"
        width="50%"
        :before-close="handleCompetitionDialogClose"
    >
      <el-form
          ref="competitionFormRef"
          :model="competitionForm"
          :rules="competitionFormRules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="competitionForm.studentId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="竞赛名称" prop="competitionName">
              <el-select
                  v-model="competitionForm.competitionName"
                  placeholder="请选择竞赛名称"
                  style="width: 100%"
                  clearable
                  filterable
              >
                <el-option
                    v-for="competition in competitionCatalogList"
                    :key="competition.id"
                    :label="competition.competitionName"
                    :value="competition.competitionName"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ competition.competitionName }}</span>
                    <span style="color: #409eff; font-size: 12px;">{{ competition.level }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="获奖等级" prop="awardLevel">
              <el-select
                  v-model="competitionForm.awardLevel"
                  placeholder="请选择获奖等级"
                  style="width: 100%"
                  clearable
              >
                <el-option label="特等奖" value="优秀奖"></el-option>
                <el-option label="一等奖" value="一等奖"></el-option>
                <el-option label="二等奖" value="二等奖"></el-option>
                <el-option label="三等奖" value="三等奖"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学年" prop="academicYear">
              <el-select
                  v-model="competitionForm.academicYear"
                  placeholder="请选择学年"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="year in academicYearList"
                    :key="year.value"
                    :label="year.label"
                    :value="year.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="获奖日期" prop="awardDate">
              <el-date-picker
                  v-model="competitionForm.awardDate"
                  type="date"
                  placeholder="请选择获奖日期"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否团队负责人" prop="isTeamLeader">
              <el-switch v-model="competitionForm.isTeamLeader"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="证明材料" prop="proof">
          <el-upload
              action="#"
              :auto-upload="false"
              :limit="3"
              :on-change="handleCompetitionProofUpload"
              :on-remove="handleCompetitionProofRemove"
              :file-list="competitionForm.proofFiles"
              list-type="picture-card"
              :before-upload="beforeProofUpload"
              multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="competitionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitCompetition" :loading="submittingCompetition">
              提交申请
            </el-button>
          </span>
      </template>
    </el-dialog>


    <!-- 学术论文对话框 -->
    <el-dialog
        v-model="paperDialogVisible"
        title="学术论文申请"
        width="50%"
        :before-close="handlePaperDialogClose"
    >
      <el-form
          ref="paperFormRef"
          :model="paperForm"
          :rules="paperFormRules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="paperForm.studentId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="论文标题" prop="paperTitle">
              <el-input v-model="paperForm.paperTitle" placeholder="请输入论文标题"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发表刊物/会议" prop="publication">
              <el-select
                  v-model="paperForm.publication"
                  placeholder="请选择发表刊物或会议"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="item in publicationOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="论文类型" prop="paperType">
              <el-select
                  v-model="paperForm.paperType"
                  placeholder="请选择论文类型"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="item in paperTypeOptions"
                    :key="item.paperType"
                    :label="item.description"
                    :value="item.paperType"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发表日期" prop="publishDate">
              <el-date-picker
                  v-model="paperForm.publishDate"
                  type="date"
                  placeholder="请选择发表日期"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贡献排名" prop="contributionRank">
              <el-input-number v-model="paperForm.contributionRank" :min="1" :max="10"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者总数" prop="authorsCount">
              <el-input-number v-model="paperForm.authorsCount" :min="1" :max="20"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学年" prop="academicYear">
              <el-select
                  v-model="paperForm.academicYear"
                  placeholder="请选择学年"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="year in academicYearList"
                    :key="year.value"
                    :label="year.label"
                    :value="year.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="证明材料" prop="proof">
          <el-upload
              action="#"
              :auto-upload="false"
              :limit="3"
              :on-change="handlePaperProofUpload"
              :on-remove="handlePaperProofRemove"
              :file-list="paperForm.proofFiles"
              list-type="picture-card"
              :before-upload="beforeProofUpload"
              multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="paperDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPaper" :loading="submittingPaper">
              提交申请
            </el-button>
          </span>
      </template>
    </el-dialog>

    <!-- 知识产权对话框 -->
    <el-dialog
        v-model="ipDialogVisible"
        title="知识产权申请"
        width="50%"
        :before-close="handleIpDialogClose"
    >
      <el-form
          ref="ipFormRef"
          :model="ipForm"
          :rules="ipFormRules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="ipForm.studentId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识产权名称" prop="name">
              <el-input v-model="ipForm.name" placeholder="请输入知识产权名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识产权类型" prop="ipType">
              <el-select
                  v-model="ipForm.ipType"
                  placeholder="请选择知识产权类型"
                  style="width: 100%"
                  filterable
                  allow-create
                  clearable
              >
                <el-option v-for="item in ipTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识产权状态" prop="ipStatus">
              <el-select
                  v-model="ipForm.ipStatus"
                  placeholder="请选择知识产权状态"
                  style="width: 100%"
                  clearable
              >
                <el-option label="已授权" value="AUTHORIZED"></el-option>
                <el-option label="实质审查" value="SUBSTANTIVE_EXAMINATION"></el-option>
                <el-option label="公开期" value="PUBLISHED"></el-option>
                <el-option label="已申请" value="APPLIED"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applicationDate">
              <el-date-picker
                  v-model="ipForm.applicationDate"
                  type="date"
                  placeholder="请选择申请日期"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学年" prop="academicYear">
              <el-select
                  v-model="ipForm.academicYear"
                  placeholder="请选择学年"
                  style="width: 100%"
                  clearable
              >
                <el-option
                    v-for="year in academicYearList"
                    :key="year.value"
                    :label="year.label"
                    :value="year.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否团队负责人" prop="isTeamLeader">
              <el-switch v-model="ipForm.isTeamLeader"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="团队人数" prop="teamSize">
              <el-input-number v-model="ipForm.teamSize" :min="1" :max="20"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请号/专利号" prop="applicationNumber">
              <el-input v-model="ipForm.applicationNumber" placeholder="请输入申请号或专利号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="证明材料" prop="proof">
          <el-upload
              action="#"
              :auto-upload="false"
              :limit="3"
              :on-change="handleIpProofUpload"
              :on-remove="handleIpProofRemove"
              :file-list="ipForm.proofFiles"
              list-type="picture-card"
              :before-upload="beforeProofUpload"
              multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="ipDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitIp" :loading="submittingIp">
              提交申请
            </el-button>
          </span>
      </template>
    </el-dialog>


    <!-- 思政成绩对话框 -->
    <el-dialog
        v-model="politicalDialogVisible"
        title="思政成绩更新"
        width="50%"
        :before-close="handlePoliticalDialogClose"
    >
      <el-form
          ref="politicalFormRef"
          :model="politicalForm"
          :rules="politicalFormRules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="politicalForm.studentId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="思政成绩" prop="score">
              <el-input v-model="politicalForm.score" placeholder="请输入思政成绩"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="politicalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePoliticalScore" :loading="submittingPolitical">
            提交更新
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 知识产权详情查看对话框 -->
    <el-dialog v-model="ipDetailVisible" title="知识产权详情" width="60%" class="ip-detail-dialog">
      <el-descriptions :column="2" border v-if="selectedIp">
        <el-descriptions-item label="知识产权名称">{{ selectedIp.name }}</el-descriptions-item>
        <el-descriptions-item label="知识产权类型">
          <el-tag type="info">{{ getIpTypeLabel(selectedIp.ipType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="知识产权状态">
          <el-tag :type="getIpStatusType(selectedIp.ipStatus)">{{ getIpStatusLabel(selectedIp.ipStatus) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请号/专利号">{{ selectedIp.applicationNumber || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="申请日期">{{ formatDate(selectedIp.applicationDate) }}</el-descriptions-item>
        <el-descriptions-item label="团队角色">
          <el-tag :type="selectedIp.isTeamLeader ? 'success' : 'info'">
            {{ selectedIp.isTeamLeader ? '负责人' : '成员' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="团队人数">{{ selectedIp.teamSize }}人</el-descriptions-item>
        <el-descriptions-item label="得分">
          <span style="font-weight: bold; color: #409eff;">{{ selectedIp.score || 0 }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="学年">{{ selectedIp.academicYear }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(selectedIp.reviewStatus)">
            {{ getStatusText(selectedIp.reviewStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="学号">{{ selectedIp.studentId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(selectedIp.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ipDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="editIp(selectedIp)">编辑</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学术论文详情对话框 -->
    <el-dialog v-model="paperDetailVisible" title="学术论文详情" width="60%" class="paper-detail-dialog">
      <el-descriptions :column="2" border v-if="selectedPaper">
        <el-descriptions-item label="论文标题">{{ selectedPaper.paperTitle }}</el-descriptions-item>
        <el-descriptions-item label="论文类型">
          <el-tag type="info">{{ selectedPaper.paperTypeDescription || selectedPaper.paperType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发表刊物/会议">{{ selectedPaper.publication }}</el-descriptions-item>
        <el-descriptions-item label="发表日期">{{ formatDate(selectedPaper.publishDate) }}</el-descriptions-item>
        <el-descriptions-item label="贡献排名">第{{ selectedPaper.contributionRank }}作者</el-descriptions-item>
        <el-descriptions-item label="作者总数">{{ selectedPaper.authorsCount }}人</el-descriptions-item>
        <el-descriptions-item label="得分"><span style="font-weight: bold; color: #409eff;">{{ selectedPaper.score || 0 }}</span></el-descriptions-item>
        <el-descriptions-item label="学年">{{ selectedPaper.academicYear }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(selectedPaper.reviewStatus)">{{ getStatusText(selectedPaper.reviewStatus) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见">{{ selectedPaper.reviewComment || '无' }}</el-descriptions-item>
        <el-descriptions-item label="证明材料">
          <a v-if="selectedPaper.proofUrl" :href="selectedPaper.proofUrl" target="_blank">点击查看</a>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(selectedPaper.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(selectedPaper.updatedAt) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Document, Delete, ZoomIn, Search, Refresh, Timer } from '@element-plus/icons-vue';
import axios from 'axios';

const store = useStore();
const currentUser = computed(() => store.getters.currentUser || {});
// 获取当前年份
const currentYear = new Date().getFullYear();

// 学年选项（奖学金评选年份）
// 显示格式：xxxx-xxxx，传给后端：xxxx
const academicYearList = ref([
  { label: `${currentYear - 1}-${currentYear}`, value: String(currentYear - 1) },
  { label: `${currentYear - 2}-${currentYear - 1}`, value: String(currentYear - 2) },
  { label: `${currentYear - 3}-${currentYear - 2}`, value: String(currentYear - 3) }
]);

const menus = [
  {name: '首页', icon: 'el-icon-document'},
  {name: '通知公告', icon: 'el-icon-bell'},
  {name: '奖学金查询', icon: 'el-icon-search'},
  {name: '候选查询', icon: 'el-icon-search'},
  {name: '学科竞赛', icon: 'el-icon-search'},
  {name: '学术论文', icon: 'el-icon-search'},
  {name: '知识产权', icon: 'el-icon-search'},
  {name: '社会服务', icon: 'el-icon-search'},
  {name: '思政成绩', icon: 'el-icon-search'},
];

const selectedMenu = ref('首页');
const loading = ref(false);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 统计数据
const statistics = reactive({
  totalScore: 0,
  academicScore: 0,
  politicalScore: 0,
  researchScore: 0,
  serviceScore: 0,
  competitionScore: 0,
  paperScore: 0,
  ipScore: 0,
  sciScore: 0
});

// 奖学金候选人数据
const scholarshipCandidates = ref([]);
const candidateList = ref([]);
const myRanking = ref(null);

// 学科竞赛数据
const competitionList = ref([]);
const competitionCatalogList = ref([]); // 竞赛目录列表
const competitionDialogVisible = ref(false);
const competitionFormRef = ref(null);
const submittingCompetition = ref(false);
const competitionForm = reactive({
  id: '',
  studentId: '',
  competitionName: '',
  awardLevel: '',
  academicYear: '',
  awardDate: '',
  isTeamLeader: false,
  teamSize: 1,
  proofFiles: [],
  reviewStatus: 'APPROVED' // 默认通过
});

const competitionFormRules = {
  competitionName: [
    {required: true, message: '请输入竞赛名称', trigger: 'blur'}
  ],
  awardLevel: [
    {required: true, message: '请选择获奖等级', trigger: 'change'}
  ],
  academicYear: [
    {required: true, message: '请选择学年', trigger: 'change'}
  ],
  awardDate: [
    {required: true, message: '请选择获奖日期', trigger: 'change'}
  ]
};

// 学术论文数据
const paperList = ref([]);
const paperDialogVisible = ref(false);
const paperFormRef = ref(null);
const submittingPaper = ref(false);
const paperForm = reactive({
  id: '',
  studentId: '',
  paperTitle: '',
  publication: '',
  publishDate: '',
  paperType: '',
  status: 'PUBLISHED',
  contributionRank: 1,
  authorsCount: 1,
  academicYear: '',
  proofUrl: '',
  reviewStatus: 'APPROVED' // 默认通过
});

const paperFormRules = {
  paperTitle: [
    {required: true, message: '请输入论文标题', trigger: 'blur'}
  ],
  publication: [
    {required: true, message: '请输入发表刊物或会议名称', trigger: 'blur'}
  ],
  paperType: [
    {required: true, message: '请选择论文类型', trigger: 'change'}
  ],
  publishDate: [
    {required: true, message: '请选择发表日期', trigger: 'change'}
  ],
  academicYear: [
    {required: true, message: '请选择学年', trigger: 'change'}
  ],
  contributionRank: [
    {required: true, message: '请输入贡献排名', trigger: 'blur'},
    {type: 'number', min: 1, message: '排名必须大于0', trigger: 'blur'}
  ],
  authorsCount: [
    {required: true, message: '请输入作者总数', trigger: 'blur'},
    {type: 'number', min: 1, message: '作者数必须大于0', trigger: 'blur'}
  ]
};

// 知识产权数据
const ipList = ref([]);
const ipDialogVisible = ref(false);
const ipFormRef = ref(null);
const submittingIp = ref(false);
const ipForm = reactive({
  id: '',
  studentId: '',
  name: '',
  ipType: '',
  ipStatus: 'APPLIED', // 默认状态为已申请
  applicationDate: '',
  academicYear: '',
  isTeamLeader: false,
  teamSize: 1,
  applicationNumber: '',
  proofUrl: '',
  proofFiles: [],
  reviewStatus: 'APPROVED' // 默认通过
});

const ipFormRules = {
  name: [
    {required: true, message: '请输入知识产权名称', trigger: 'blur'}
  ],
  ipType: [
    {required: true, message: '请选择知识产权类型', trigger: 'change'}
  ],
  ipStatus: [
    {required: true, message: '请选择知识产权状态', trigger: 'change'}
  ],
  applicationDate: [
    {required: true, message: '请选择申请日期', trigger: 'change'}
  ],
  academicYear: [
    {required: true, message: '请选择学年', trigger: 'change'}
  ],
  teamSize: [
    {required: true, message: '请输入团队人数', trigger: 'blur'},
    {type: 'number', min: 1, message: '团队人数必须大于0', trigger: 'blur'}
  ]
};

// 社会服务数据
const socialServiceDialogVisible = ref(false);
const socialServiceFormRef = ref(null);
const submitting = ref(false);
const socialServiceForm = reactive({
  id: '',
  studentId: '',
  name: '',
  service_type: '',
  activity_name: '',
  academic_year: '',
  service_date: [],
  description: '',
  proof_files: []
});

// 社会服务规则数据
const socialServiceList = ref([]);
const socialServiceRules = ref([]); // 从数据库获取的服务类型规则

const socialServiceFormRules = {
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'}
  ],
  service_type: [
    {required: true, message: '请选择服务类型', trigger: 'change'}
  ],
  activity_name: [
    {required: true, message: '请输入服务名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur'}
  ],
  academic_year: [
    {required: true, message: '请选择学年', trigger: 'change'}
  ],
  service_date: [
    {required: true, message: '请选择服务日期', trigger: 'change'}
  ],
  description: [
    {required: true, message: '请输入服务描述', trigger: 'blur'},
    {min: 10, message: '至少输入10个字符的描述', trigger: 'blur'}
  ]
};

// 根据选择的服务类型获取规则信息
const selectedServiceRule = computed(() => {
  if (!socialServiceForm.service_type || !Array.isArray(socialServiceRules.value)) {
    return null;
  }
  return socialServiceRules.value.find(rule => rule.ruleKey === socialServiceForm.service_type);
});

// 思政成绩数据
const politicalScore = reactive({
  baseScore: 0,
  honorScore: 0,
  advisorScore: 0,
  deduction: 0,
  totalScore: 0
});

// 通知公告数据
const notices = ref([
  {
    id: 1,
    title: '2024年奖学金评选通知',
    content: '请各位同学及时查看奖学金评选相关信息',
    date: '2024-06-15',
    type: 'important'
  },
  {
    id: 2,
    title: '学科竞赛获奖公示',
    content: '2024年学科竞赛获奖名单已公示，请及时查看',
    date: '2024-06-10',
    type: 'normal'
  },
  {
    id: 3,
    title: '学术论文发表统计',
    content: '请各位同学及时更新学术论文发表情况',
    date: '2024-06-05',
    type: 'normal'
  }
]);

// 通用数据
const previewVisible = ref(false);
const previewImageUrl = ref('');

// 菜单切换
const selectMenu = (menu) => {
  selectedMenu.value = menu.name;
  loadDataByMenu(menu.name);
};

// 根据菜单加载数据
const loadDataByMenu = async (menuName) => {
  switch (menuName) {
    case '首页':
      await loadDashboardData();
      break;
    case '奖学金查询':
    case '候选查询':
      await loadScholarshipAndCandidateData();
      break;
    case '学科竞赛':
      await loadCompetitionData();
      break;
    case '学术论文':
      await loadPaperData();
      break;
    case '知识产权':
      await loadIpData();
      break;
    case '社会服务':
      await loadSocialServiceData();
      break;
    case '思政成绩':
      await loadPoliticalData();
      break;
  }
};

// 加载首页数据
const loadDashboardData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      console.log('用户ID不存在，跳过数据加载');
      return;
    }

    // 计算 academicYear（评选年份的前一年）
    const currentYear = new Date().getFullYear();
    // 奖学金评选规则：当前年份评选上一年的成果
    // 例如：2025年评选2024年的成果
    const academicYear = String(currentYear - 1);

    console.log('开始加载首页数据，学生ID:', studentId, '学年:', academicYear);

    // 并行加载各项数据
    const [
      academicScore,
      politicalScore,
      serviceScore,
      competitionScore,
      paperScore,
      ipScore
    ] = await Promise.all([
      // 学业成绩
      axios.get(`/grade/academicAchievement/${studentId}`)
          .then(response => {
            console.log('学业成绩响应:', response.data);
            return response.data?.data || 0;
          })
          .catch((error) => {
            console.error('学业成绩请求失败:', error);
            return 0;
          }),

      // 思政成绩（需要添加学年参数）
      axios.get(`/political/student/${studentId}`, {
        params: { academicYear }
      })
          .then(response => {
            console.log('思政成绩响应:', response.data);
            return response.data?.data?.totalScore || 0;
          })
          .catch((error) => {
            console.error('思政成绩请求失败:', error);
            return 0;
          }),

      // 社会服务
      axios.get(`/socialService/score/total`, {
        params: {
          studentId,
          academicYear
        }
      })
          .then(response => {
            console.log('社会服务响应:', response.data);
            return response.data?.data || 0;
          })
          .catch((error) => {
            console.error('社会服务请求失败:', error);
            return 0;
          }),

      // 学科竞赛（修复接口路径）
      axios.get(`/competitionParticipation/score/${studentId}`, {
        params: { academicYear }
      })
          .then(response => {
            console.log('学科竞赛响应:', response.data);
            // 直接返回数据，不需要.data.data
            return response.data?.data || 0;
          })
          .catch((error) => {
            console.error('学科竞赛请求失败:', error);
            return 0;
          }),

      // 科研论文（需要添加学年参数）
      axios.get(`/researchPaper/totalScore/${studentId}`, {
        params: { academicYear }
      })
          .then(response => {
            console.log('科研论文响应:', response.data);
            return response.data?.data || 0;
          })
          .catch((error) => {
            console.error('科研论文请求失败:', error);
            return 0;
          }),

      // 知识产权（修复接口路径）
      axios.get(`/intellectualProperty/score/total/${studentId}`, {
        params: { academicYear }
      })
          .then(response => {
            console.log('知识产权响应:', response.data);
            // 直接返回数据，不需要.data.data
            return response.data?.data || 0;
          })
          .catch((error) => {
            console.error('知识产权请求失败:', error);
            return 0;
          })
    ]);

    // 更新统计数据
    statistics.academicScore = Number(academicScore) || 0;
    statistics.politicalScore = Number(politicalScore) || 0;
    statistics.serviceScore = Number(serviceScore) || 0;
    statistics.competitionScore = Number(competitionScore) || 0;
    statistics.paperScore = Number(paperScore) || 0;
    statistics.ipScore = Number(ipScore) || 0;

    statistics.sciScore = statistics.competitionScore + statistics.politicalScore + statistics.ipScore;

    // 计算总分
    statistics.totalScore =
        statistics.academicScore +
        statistics.politicalScore +
        statistics.serviceScore +
        statistics.competitionScore +
        statistics.paperScore +
        statistics.ipScore;

    console.log('首页数据加载完成:', {
      academicScore: statistics.academicScore,
      politicalScore: statistics.politicalScore,
      serviceScore: statistics.serviceScore,
      competitionScore: statistics.competitionScore,
      paperScore: statistics.paperScore,
      ipScore: statistics.ipScore,
      totalScore: statistics.totalScore
    });

  } catch (error) {
    console.error('加载首页数据失败:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载奖学金数据和候选人数据统一处理
const loadScholarshipAndCandidateData = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/scholarship/candidates').catch(() => ({ data: { status: 200, data: [] } }));
    const data = Array.isArray(response.data.data) ? response.data.data : [];
    // 奖学金管理（奖学金查询）只显示当前用户，isQualified 强制为 true
    scholarshipCandidates.value = data.filter(
        candidate => candidate.studentId === currentUser.value?.userId
    ).map(candidate => ({ ...candidate, isQualified: true }));
    // 候选查询显示所有，isQualified 也强制为 true
    candidateList.value = data.map(candidate => ({ ...candidate, isQualified: true }));
  } catch (error) {
    console.error('加载奖学金数据失败:', error);
    ElMessage.error('加载奖学金数据失败');
    scholarshipCandidates.value = [];
    candidateList.value = [];
  } finally {
    loading.value = false;
  }
};

const loadPoliticalData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      politicalScore.baseScore = 0;
      politicalScore.honorScore = 0;
      politicalScore.advisorScore = 0;
      politicalScore.deduction = 0;
      politicalScore.totalScore = 0;
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 调用思政成绩接口（带学年参数）
    const response = await axios.get(`/political/student/${studentId}`, {
      params: { academicYear }
    }).catch(() => ({ data: { data: { totalScore: 0 } }}));

    // 更新思政成绩数据
    const data = response.data.data || {};
    politicalScore.baseScore = data.baseScore || 0;
    politicalScore.honorScore = data.honorScore || 0;
    politicalScore.advisorScore = data.advisorScore || 0;
    politicalScore.deduction = data.deduction || 0;
    politicalScore.totalScore = data.totalScore || 0;

  } catch (error) {
    console.error('加载思政成绩失败:', error);
    ElMessage.error('加载思政成绩失败');
  } finally {
    loading.value = false;
  }
};
// 加载学科竞赛数据
const loadCompetitionData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      competitionList.value = [];
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 获取学生的参赛记录（带学年参数）
    const response = await axios.get(`/competitionParticipation/student/${studentId}/year/${academicYear}`).catch(() => ({ data: { status: 200, data: [] } }));
    competitionList.value = Array.isArray(response.data.data) ? response.data.data : [];
    console.log('学科竞赛数据:', response.data.data);
  } catch (error) {
    console.error('加载学科竞赛数据失败:', error);
    ElMessage.error('加载学科竞赛数据失败');
    competitionList.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载学术论文数据
const loadPaperData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      paperList.value = [];
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 获取学生的论文记录（带学年参数）
    const response = await axios.get(`/researchPaper/student/${studentId}`, {
      params: { academicYear }
    }).catch(() => ({ data: { status: 200, data: [] } }));
    paperList.value = Array.isArray(response.data.data) ? response.data.data : [];
  } catch (error) {
    console.error('加载学术论文数据失败:', error);
    ElMessage.error('加载学术论文数据失败');
    paperList.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载知识产权数据
const loadIpData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      ipList.value = [];
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 获取学生的知识产权记录（带学年参数）
    const response = await axios.get(`/intellectualProperty/student/${studentId}`, {
      params: { academicYear }
    }).catch(() => ({ data: { data: [] } }));
    ipList.value = Array.isArray(response.data.data) ? response.data.data : [];
  } catch (error) {
    console.error('加载知识产权数据失败:', error);
    ElMessage.error('加载知识产权数据失败');
    ipList.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载社会服务规则
const loadSocialServiceRules = async () => {
  try {
    const response = await axios.get('/socialService/rules').catch(() => ({ data: { status: 200, data: {} } }));
    if (response.data.status === 200) {
      const rulesMap = response.data.data || {};
      socialServiceRules.value = Object.values(rulesMap).map(rule => ({
        ruleKey: rule.ruleKey,
        ruleName: rule.ruleName,
        ruleType: rule.ruleType,
        scoreValue: rule.scoreValue,
        description: rule.description,
        durationRequired: rule.durationRequired,
        maxTimes: rule.maxTimes
      }));
    } else {
      socialServiceRules.value = [];
    }
  } catch (error) {
    console.error('加载社会服务规则失败:', error);
    ElMessage.error('加载社会服务规则失败');
    socialServiceRules.value = [];
  }
};

const loadSocialServiceData = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      socialServiceList.value = [];
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 获取学生的社会服务记录（带学年参数）
    const response = await axios.get(`/socialService/student/${studentId}`, {
      params: { academicYear }
    }).catch(() => ({ data: { data: [] } }));
    socialServiceList.value = Array.isArray(response.data.data) ? response.data.data : [];
  } catch (error) {
    console.error('获取社会服务记录失败:', error);
    ElMessage.error('获取社会服务记录失败，请稍后重试');
    socialServiceList.value = [];
  } finally {
    loading.value = false;
  }
};

// 候选人相关
const candidateDetailVisible = ref(false);
const selectedCandidate = ref(null);
const candidateSearchKeyword = ref('');
const candidateFilterType = ref('');

// 筛选后的候选人列表
const filteredCandidateList = computed(() => {
  let filtered = Array.isArray(candidateList.value) ? candidateList.value : [];

  // 按关键词搜索
  if (candidateSearchKeyword.value) {
    const keyword = candidateSearchKeyword.value.toLowerCase();
    filtered = filtered.filter(candidate =>
        candidate.studentId?.toLowerCase().includes(keyword) ||
        candidate.name?.toLowerCase().includes(keyword)
    );
  }

  // 按奖学金类型筛选
  if (candidateFilterType.value) {
    filtered = filtered.filter(candidate =>
        candidate.scholarshipType === candidateFilterType.value
    );
  }

  return Array.isArray(filtered) ? filtered : [];
});

// 候选人筛选方法
const filterCandidates = () => {
  // 计算属性会自动更新，这里不需要额外操作
  console.log('筛选候选人:', Array.isArray(filteredCandidateList?.value) ? filteredCandidateList.value.length : 0);
};

// 查看候选人详情
const viewCandidateDetail = (candidate) => {
  selectedCandidate.value = candidate;
  candidateDetailVisible.value = true;
};

// 社会服务相关方法
const showSocialServiceDialog = async () => {
  // 重新加载社会服务规则，确保数据是最新的
  await loadSocialServiceRules();

  socialServiceForm.studentId = currentUser.value?.userId || '';
  socialServiceForm.name = currentUser.value?.username || '';
  socialServiceDialogVisible.value = true;
};

const submitSocialServiceForm = async () => {
  try {
    submitting.value = true;
    await socialServiceFormRef.value.validate();
    const formData = {
      studentId: currentUser.value.userId,
      name: currentUser.value.username,
      serviceType: socialServiceForm.service_type,
      activityName: socialServiceForm.activity_name,
      academicYear: socialServiceForm.academic_year,
      startDate: socialServiceForm.service_date[0],
      endDate: socialServiceForm.service_date[1],
      review_comment: socialServiceForm.description
    };
    let response;
    if (socialServiceForm.id) {
      response = await axios.put(`/socialService/${socialServiceForm.id}`, formData);
    } else {
      // SocialServiceController: /socialService/add POST
      response = await axios.post('/socialService/add', formData);
    }

    console.log(response.data.data);
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success(socialServiceForm.id ? '更新成功' : '添加成功');
      await loadSocialServiceData();
      socialServiceDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error('提交失败: ' + (error.response?.data?.msg || error.message));
  } finally {
    submitting.value = false;
  }
};

const handleCloseDialog = () => {
  socialServiceDialogVisible.value = false;
  socialServiceForm.id = '';
  socialServiceForm.service_type = '';
  socialServiceForm.activity_name = '';
  socialServiceForm.academic_year = '';
  socialServiceForm.service_date = [];
  socialServiceForm.description = '';
  socialServiceForm.proof_files = [];
};

const beforeProofUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return false; // 阻止自动上传
};

const handleProofUpload = (file, fileList) => {
  socialServiceForm.proof_files = fileList;
};

const handleProofRemove = (file, fileList) => {
  socialServiceForm.proof_files = fileList;
};

const viewProof = (row) => {
  if (row.proof_files && row.proof_files.length > 0) {
    previewImageUrl.value = row.proof_files[0].url;
    previewVisible.value = true;
  } else {
    ElMessage.info('暂无证明材料');
  }
};

// 编辑和删除方法
const editSocialService = (row) => {
  socialServiceForm.id = row.id;
  socialServiceForm.studentId = row.studentId;
  socialServiceForm.name = row.name;
  socialServiceForm.service_type = row.service_type;
  socialServiceForm.activity_name = row.activity_name;
  socialServiceForm.academic_year = row.academic_year;
  socialServiceForm.service_date = [row.start_time, row.end_time];
  socialServiceForm.description = row.description;
  socialServiceForm.proof_files = row.proof_files || [];
  socialServiceDialogVisible.value = true;
};

const deleteSocialService = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // SocialServiceController: /socialService/{id} DELETE
    const response = await axios.delete(`/socialService/${id}`);
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('删除成功');
      await loadSocialServiceData();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 学科竞赛相关方法
const showCompetitionDialog = async () => {
  // 加载竞赛目录列表
  await loadCompetitionCatalog();

  competitionForm.studentId = currentUser.value?.userId || '';
  competitionDialogVisible.value = true;
};

const submitCompetition = async () => {
  try {
    submittingCompetition.value = true;
    await competitionFormRef.value.validate();

    // 1. 获取 competitionId
    const competitionIdResponse = await axios.get('/competitionCatalog/getId', {
      params: { name: competitionForm.competitionName }
    });

    console.log('竞赛ID响应:', competitionIdResponse.data);

    if (!competitionIdResponse.data.data) {
      throw new Error("未找到对应的竞赛信息");
    }

    // 2. 提交表单数据
    const formData = {
      studentId: currentUser.value.userId,
      competitionId: competitionIdResponse.data.data,
      participationDate: competitionForm.awardDate,
      awardLevel: competitionForm.awardLevel,
      academicYear: competitionForm.academicYear,
      isTeamLeader: competitionForm.isTeamLeader ? 1 : 0, // 转换为整数
      teamSize: competitionForm.teamSize || 1,
      score: 0, // 初始分数为0，后端会自动计算
      proofUrl: "", // 暂时为空
      status: "approved", // 默认通过
      reviewComment: "自动通过" // 添加审核意见字段
    };

    console.log('准备发送的数据:', formData);

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };

    let response;
    if (competitionForm.id) {
      response = await axios.put('/competitionParticipation', formData, config);
    } else {
      response = await axios.post('/competitionParticipation', formData, config);
    }

    console.log('服务器响应:', response.data);

    if (response.data.code === 200 || response.data.status === 200) {
      ElMessage.success("提交成功");
      competitionDialogVisible.value = false;
      await loadCompetitionData(); // 重新加载学生的参赛记录
    } else {
      ElMessage.error(response.data.msg || response.data.message || "提交失败");
    }
  } catch (error) {
    console.error('提交失败详细信息:', error);
    console.error('错误响应数据:', error.response?.data);
    console.error('错误状态码:', error.response?.status);
    console.error('错误状态文本:', error.response?.statusText);

    if (error.response?.data?.message) {
      ElMessage.error('提交失败: ' + error.response.data.message);
    } else if (error.response?.data?.msg) {
      ElMessage.error('提交失败: ' + error.response.data.msg);
    } else if (error.message) {
      ElMessage.error('提交失败: ' + error.message);
    } else {
      ElMessage.error('提交失败，请检查网络连接');
    }
  } finally {
    submittingCompetition.value = false;
  }
};
const editCompetition = (row) => {
  Object.assign(competitionForm, row)
  showCompetitionForm.value = true
}

const deleteCompetition = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // CompetitionParticipationController: /competitionParticipation/{id} DELETE
    const response = await axios.delete(`/competitionParticipation/${id}`);
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('删除成功');
      await loadCompetitionData();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
}

// 学术论文相关方法
const queryPapers = async () => {
  if (!paperQueryForm.studentId) {
    ElMessage.warning('请输入学生ID')
    return
  }
  try {
    const response = await axios.get(`/scholarship/paper/student/${paperQueryForm.studentId}`)
    papers.value = Array.isArray(response.data.data) ? response.data.data : []
    ElMessage.success('查询成功')
  } catch (error) {
    console.error('查询学术论文失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  }
}

const submitPaper = async () => {
  try {
    submittingPaper.value = true;
    await paperFormRef.value.validate();

    // 格式化日期为Date对象
    let publishDate = paperForm.publishDate;
    if (typeof publishDate === 'string') {
      publishDate = new Date(publishDate);
    }

    const formData = {
      id: paperForm.id || null,
      studentId: currentUser.value?.userId.toString(), // 确保是字符串类型
      paperTitle: paperForm.paperTitle,
      publication: paperForm.publication,
      publishDate: publishDate, // 保持为Date对象，让后端处理转换
      paperType: paperForm.paperType,
      status: paperForm.status || 'PUBLISHED',
      contributionRank: Number(paperForm.contributionRank),
      authorsCount: Number(paperForm.authorsCount),
      academicYear: paperForm.academicYear,
      proofUrl: paperForm.proofUrl || '',
      reviewStatus: 'APPROVED', // 默认通过
      reviewComment: '自动通过', // 默认审核意见
      score: paperForm.score || null
    };

    let response;
    if (paperForm.id) {
      response = await axios.put(`/researchPaper`, formData);
    } else {
      response = await axios.post('/researchPaper', formData);
    }

    if (response.data.success || response.data.status === 200) {
      ElMessage.success(paperForm.id ? '更新成功' : '添加成功');
      paperDialogVisible.value = false;
      await loadPaperData();
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('提交学术论文失败:', error);
    ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message));
  } finally {
    submittingPaper.value = false;
  }
};

const formatDate = (dateString) => {
  if (!dateString) return '--';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
};

const calculateDuration = (startDate, endDate) => {
  if (!startDate || !endDate) return '--';
  const start = new Date(startDate);
  const end = new Date(endDate);
  const diff = end - start;
  const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
  return `${days}天`;
};

const editPaper = (row) => {
  Object.assign(paperForm, row);
  paperDialogVisible.value = true;
};

const deletePaper = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await axios.delete(`/researchPaper/${id}`);
    if (response.data.success || response.data.status === 200) {
      ElMessage.success('删除成功');
      await loadPaperData();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学术论文失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 知识产权相关方法
const showIpDialog = () => {
  ipForm.studentId = currentUser.value?.userId || '';
  ipDialogVisible.value = true;
};

const submitIp = async () => {
  try {
    submittingIp.value = true;
    await ipFormRef.value.validate();

    const formData = {
      id: ipForm.id || null,
      studentId: currentUser.value?.userId,
      name: ipForm.name,
      ipType: ipForm.ipType,
      ipStatus: ipForm.ipStatus,
      applicationDate: ipForm.applicationDate,
      academicYear: ipForm.academicYear,
      isTeamLeader: ipForm.isTeamLeader ? 1 : 0,
      teamSize: ipForm.teamSize,
      applicationNumber: ipForm.applicationNumber,
      proofUrl: ipForm.proofUrl || '',
      reviewStatus: 'APPROVED' // 默认通过
    };

    console.log('提交的知识产权数据:', formData);

    let response;
    if (ipForm.id) {
      response = await axios.put(`/intellectualProperty`, formData);
    } else {
      response = await axios.post('/intellectualProperty', formData);
    }

    console.log('服务器响应:', response.data);

    if (response.data.status === 200) {
      ElMessage.success(ipForm.id ? '更新成功' : '添加成功');
      ipDialogVisible.value = false;
      // 重置表单
      Object.assign(ipForm, {
        id: '',
        studentId: '',
        name: '',
        ipType: '',
        ipStatus: 'APPLIED',
        applicationDate: '',
        academicYear: '',
        isTeamLeader: false,
        teamSize: 1,
        applicationNumber: '',
        proofUrl: '',
        proofFiles: [],
        reviewStatus: 'APPROVED' // 默认通过
      });
      await loadIpData();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('提交知识产权失败:', error);
    console.error('错误响应数据:', error.response?.data);
    ElMessage.error('提交失败: ' + (error.response?.data?.msg || error.message));
  } finally {
    submittingIp.value = false;
  }
};

const editIp = (row) => {
  Object.assign(ipForm, row);
  ipDialogVisible.value = true;
};

const deleteIp = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await axios.delete(`/intellectualProperty/${id}`);
    if (response.data.status === 200) {
      ElMessage.success('删除成功');
      await loadIpData();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除知识产权失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

const handleIpProofUpload = (file, fileList) => {
  ipForm.proofFiles = fileList;
};

const handleIpProofRemove = (file, fileList) => {
  ipForm.proofFiles = fileList;
};

const handlePaperProofUpload = (file, fileList) => {
  paperForm.proofFiles = fileList;
};

const handlePaperProofRemove = (file, fileList) => {
  paperForm.proofFiles = fileList;
};

// 思政成绩相关方法
const queryPoliticalScore = async () => {
  if (!politicalQueryForm.studentId) {
    ElMessage.warning('请输入学生ID')
    return
  }
  try {
    const response = await axios.get(`/political/student/${politicalQueryForm.studentId}`)
    politicalScore.value = response.data.data
    ElMessage.success('查询成功')
  } catch (error) {
    console.error('查询思政成绩失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  }
}

const submitPoliticalScore = async () => {
  try {
    submittingPolitical.value = true;
    await politicalFormRef.value.validate();
    // PoliticalController: /political/score?studentId=xxx&newScore=xx PUT
    const response = await axios.put(`/political/score?studentId=${politicalForm.studentId}&newScore=${politicalForm.score}`);
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('更新成功');
      politicalDialogVisible.value = false;
      await loadPoliticalData();
    } else {
      ElMessage.error(response.data.message || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败');
  } finally {
    submittingPolitical.value = false;
  }
};

const updatePoliticalScore = async () => {
  try {
    submittingPolitical.value = true;
    await politicalFormRef.value.validate();
    // PoliticalController: /political/score?studentId=xxx&newScore=xx PUT
    const response = await axios.put(`/political/score?studentId=${politicalForm.studentId}&newScore=${politicalForm.score}`);
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('更新成功');
      politicalDialogVisible.value = false;
      await loadPoliticalData();
    } else {
      ElMessage.error(response.data.message || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败');
  } finally {
    submittingPolitical.value = false;
  }
};

// 社会服务相关方法
const queryServices = async () => {
  if (!serviceQueryForm.studentId) {
    ElMessage.warning('请输入学生ID')
    return
  }
  try {
    const response = await axios.get(`/socialService/student/${serviceQueryForm.studentId}`)
    services.value = Array.isArray(response.data.data) ? response.data.data : []
    ElMessage.success('查询成功')
  } catch (error) {
    console.error('查询社会服务失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  }
}

const submitService = async () => {
  try {
    const response = await axios.post('/socialService/add', serviceForm)
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('添加成功')
      showServiceForm.value = false
      queryServices()
      Object.assign(serviceForm, {
        studentId: '',
        serviceType: '',
        serviceHours: 0,
        serviceDate: '',
        description: ''
      })
    } else {
      ElMessage.error(response.data.message || '添加失败')
    }
  } catch (error) {
    console.error('添加社会服务失败:', error)
    ElMessage.error('添加失败，请稍后重试')
  }
}

const editService = (row) => {
  Object.assign(serviceForm, row)
  showServiceForm.value = true
}

const deleteService = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const response = await axios.delete(`/socialService/${id}`)
    if (response.data.status === 200 || response.data.success) {
      ElMessage.success('删除成功')
      queryServices()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除社会服务失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const getStatusText = (statusCode) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  };
  return statusMap[statusCode] || '未知状态';
};

const getStatusType = (statusCode) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  };
  return typeMap[statusCode] || 'info';
};

const getIpStatusType = (status) => {
  const typeMap = {
    '已授权': 'success',
    '已申请': 'warning',
    '未申请': 'info'
  };
  return typeMap[status] || 'info';
};

// 页面初始化
onMounted(() => {
  // 延迟加载数据，确保用户信息已经加载
  setTimeout(async () => {
    await loadSocialServiceRules(); // 加载社会服务规则
    await loadDashboardData();
    await loadScholarshipAndCandidateData(); // 加载奖学金数据和候选人数据
    await loadRankingData(); // 加载排名数据

    // 启动自动刷新定时器
    startAutoRefresh();
  }, 100);
});

// 自动刷新相关
const autoRefreshInterval = ref(null);
const autoRefreshEnabled = ref(true);
const refreshInterval = 30000; // 30秒刷新一次

// 启动自动刷新
const startAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value);
  }

  autoRefreshInterval.value = setInterval(() => {
    if (autoRefreshEnabled.value) {
      refreshCurrentData();
    }
  }, refreshInterval);
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value);
    autoRefreshInterval.value = null;
  }
};

// 刷新当前页面数据
const refreshCurrentData = async () => {
  try {
    console.log('自动刷新数据...');
    switch (selectedMenu.value) {
      case '奖学金查询':
        await loadScholarshipAndCandidateData(true); // 静默刷新
        await loadRankingData(true); // 静默刷新
        break;
      case '候选查询':
        await loadScholarshipAndCandidateData(true); // 静默刷新
        break;
      case '首页':
        await loadDashboardData();
        break;
      case '学科竞赛':
        await loadCompetitionData();
        break;
      case '学术论文':
        await loadPaperData();
        break;
      case '知识产权':
        await loadIpData();
        break;
      case '社会服务':
        await loadSocialServiceData();
        break;
      case '思政成绩':
        await loadPoliticalData();
        break;
    }
  } catch (error) {
    console.error('自动刷新失败:', error);
  }
};

// 切换自动刷新状态
const toggleAutoRefresh = () => {
  autoRefreshEnabled.value = !autoRefreshEnabled.value;
  if (autoRefreshEnabled.value) {
    ElMessage.success('已开启自动刷新');
  } else {
    ElMessage.info('已关闭自动刷新');
  }
};

// 手动刷新当前页面
const manualRefresh = async () => {
  try {
    loading.value = true;
    await refreshCurrentData();
    ElMessage.success('数据已刷新');
  } catch (error) {
    console.error('手动刷新失败:', error);
    ElMessage.error('刷新失败');
  } finally {
    loading.value = false;
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh();
});

// 思政成绩相关
const politicalDialogVisible = ref(false);
const politicalFormRef = ref(null);
const submittingPolitical = ref(false);
const politicalForm = reactive({
  studentId: '',
  score: 0
});

const politicalFormRules = {
  studentId: [
    {required: true, message: '请输入学号', trigger: 'blur'}
  ],
  score: [
    {required: true, message: '请输入思政成绩', trigger: 'blur'},
    {type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间', trigger: 'blur'}
  ]
};

// 对话框关闭处理函数
const handleCompetitionDialogClose = () => {
  competitionDialogVisible.value = false;
  competitionForm.studentId = '';
  competitionForm.competitionId = '';
  competitionForm.awardLevel = '';
  competitionForm.academicYear = '';
  competitionForm.isTeamLeader = false;
  competitionForm.teamSize = 1;
};

const handlePaperDialogClose = () => {
  paperDialogVisible.value = false;
  Object.assign(paperForm, {
    id: '',
    studentId: '',
    paperTitle: '',
    publication: '',
    publishDate: '',
    paperType: '',
    status: 'PUBLISHED',
    contributionRank: 1,
    authorsCount: 1,
    academicYear: '',
    proofUrl: '',
    reviewStatus: 'PENDING'
  });
};

const handleIpDialogClose = () => {
  ipDialogVisible.value = false;
  Object.assign(ipForm, {
    id: '',
    studentId: '',
    name: '',
    ipType: '',
    ipStatus: '',
    applicationDate: '',
    academicYear: '',
    isTeamLeader: false,
    teamSize: 1,
    applicationNumber: '',
    proofUrl: '',
    proofFiles: [],
    reviewStatus: 'PENDING'
  });
};

const handlePoliticalDialogClose = () => {
  politicalDialogVisible.value = false;
  politicalForm.studentId = '';
  politicalForm.score = 0;
};

// 加载竞赛目录数据
const loadCompetitionCatalog = async () => {
  try {
    const response = await axios.get('/competitionCatalog').catch(() => ({ data: { status: 200, data: [] } }));
    competitionCatalogList.value = Array.isArray(response.data.data) ? response.data.data : [];
  } catch (error) {
    console.error('加载竞赛目录失败:', error);
    ElMessage.error('加载竞赛目录失败');
    competitionCatalogList.value = [];
  }
};

const getApprovedIpCount = () => {
  return Array.isArray(ipList?.value) ? ipList.value.filter(ip => ip.reviewStatus === 'APPROVED' || ip.reviewStatus === 1).length : 0;
};

const getTotalIpScore = () => {
  return ipList.value.reduce((total, ip) => total + (ip.score || 0), 0);
};

const getTeamLeaderCount = () => {
  return Array.isArray(ipList?.value) ? ipList.value.filter(ip => ip.isTeamLeader).length : 0;
};

const ipSearchKeyword = ref('');
const ipFilterType = ref('');
const ipFilterStatus = ref('');

// 筛选后的知识产权列表
const filteredIpList = computed(() => {
  if (!Array.isArray(ipList.value)) {
    return [];
  }

  let filtered = ipList.value;

  // 按关键词搜索
  if (ipSearchKeyword.value) {
    const keyword = ipSearchKeyword.value.toLowerCase();
    filtered = filtered.filter(ip =>
        ip.name?.toLowerCase().includes(keyword) ||
        ip.applicationNumber?.toLowerCase().includes(keyword)
    );
  }

  // 按知识产权类型筛选
  if (ipFilterType.value) {
    filtered = filtered.filter(ip => ip.ipType === ipFilterType.value);
  }

  // 按审核状态筛选
  if (ipFilterStatus.value) {
    filtered = filtered.filter(ip => ip.reviewStatus === ipFilterStatus.value);
  }

  return filtered;
});

const filterIpList = () => {
  // 计算属性会自动更新，这里不需要额外操作
  console.log('过滤知识产权列表:', ipSearchKeyword.value, ipFilterType.value, ipFilterStatus.value);
};

// 知识产权详情查看
const ipDetailVisible = ref(false);
const selectedIp = ref(null);

const viewIpDetail = (ip) => {
  selectedIp.value = ip;
  ipDetailVisible.value = true;
};

// 导出知识产权数据
const exportIpData = () => {
  try {
    const data = filteredIpList.value.map(ip => ({
      '知识产权名称': ip.name,
      '知识产权类型': ip.ipTypeDescription || ip.ipType,
      '知识产权状态': ip.ipStatus,
      '申请号/专利号': ip.applicationNumber || '',
      '申请日期': formatDate(ip.applicationDate),
      '团队角色': ip.isTeamLeader ? '负责人' : '成员',
      '团队人数': ip.teamSize,
      '得分': ip.score || 0,
      '学年': ip.academicYear,
      '审核状态': getStatusText(ip.reviewStatus),
      '学号': ip.studentId
    }));

    // 创建CSV内容
    const headers = Object.keys(data[0] || {});
    const csvContent = [
      headers.join(','),
      ...data.map(row => headers.map(header => `"${row[header]}"`).join(','))
    ].join('\n');

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `知识产权数据_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('数据导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
};

// 知识产权选项数据
const ipTypeOptions = ref([]);

// 加载知识产权类型选项
const loadIpOptions = async () => {
  try {
    const typeRes = await axios.get('/intellectualProperty/types');
    ipTypeOptions.value = Array.isArray(typeRes.data.data) ? typeRes.data.data : [];
  } catch (e) {
    ipTypeOptions.value = [];
  }
};

onMounted(async () => {
  await loadIpOptions();
});

const getIpTypeLabel = (item) => {
  const typeMap = {
    'INVENTION_PATENT': '发明专利',
    'UTILITY_MODEL': '实用新型专利',
    'SOFTWARE_COPYRIGHT': '软件著作权'
  };
  return typeMap[item] || item;
};

const getIpStatusLabel = (status) => {
  const statusMap = {
    'AUTHORIZED': '已授权',
    'SUBSTANTIVE_EXAMINATION': '实质审查',
    'PUBLISHED': '公开期',
    'APPLIED': '已申请'
  };
  return statusMap[status] || status;
};

const paperDetailVisible = ref(false);
const selectedPaper = ref(null);
const viewPaperDetail = (row) => {
  selectedPaper.value = row;
  paperDetailVisible.value = true;
};

// 修复：新建学术论文对话框方法
function showPaperDialog() {
  Object.assign(paperForm, {
    id: '',
    studentId: currentUser.value?.userId || '',
    paperTitle: '',
    publication: '',
    publishDate: '',
    paperType: '',
    status: 'PUBLISHED',
    contributionRank: 1,
    authorsCount: 1,
    academicYear: '',
    proofUrl: '',
    reviewStatus: 'PENDING'
  });
  paperDialogVisible.value = true;
}

// 论文类型选项
const paperTypeOptions = ref([]);
const loadPaperTypeOptions = async () => {
  try {
    const res = await axios.get('/paperScoringRule');
    paperTypeOptions.value = Array.isArray(res.data.data) ? res.data.data : [];
  } catch (e) {
    paperTypeOptions.value = [];
  }
};

onMounted(async () => {
  await loadPaperTypeOptions();
  // 你原有的其它初始化代码（如 loadIpOptions 等）
});

// 发表刊物/会议选项
const publicationOptions = ref([]);
const loadPublicationOptions = async () => {
  try {
    const res = await axios.get('/paperScoringRule/PaperType');
    publicationOptions.value = Array.isArray(res.data.data) ? res.data.data : [];
  } catch (e) {
    publicationOptions.value = [];
  }
};

onMounted(async () => {
  await loadPublicationOptions();
  // ...原有其它初始化...
});

// 查询我的排名
const queryMyRanking = async () => {
  try {
    loading.value = true;
    const studentId = currentUser.value?.userId;
    if (!studentId) {
      ElMessage.warning('请先登录');
      return;
    }

    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);

    // 默认查询国家奖学金，如果没有申请记录则提示用户
    const response = await axios.get(`/scholarship/ranking/student/${studentId}`, {
      params: {
        academicYear: academicYear,
        scholarshipType: '国家奖学金'
      }
    });

    if (response.data.status === 200) {
      myRanking.value = response.data.data;
      ElMessage.success('查询排名成功');
    } else {
      ElMessage.warning('暂无排名信息');
    }
  } catch (error) {
    console.error('查询排名失败:', error);
    if (error.response?.status === 404) {
      ElMessage.warning('暂无排名信息');
    } else {
      ElMessage.error('查询失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

const selectedGrade = ref(2);
const selectedScholarshipType = ref('国家奖学金');
const rankingList = ref([]);

const loadRankingData = async (silent = false) => {
  try {
    if (!silent) loading.value = true;
    // 计算学年（当前年份评选上一年的成果）
    const currentYear = new Date().getFullYear();
    const academicYear = String(currentYear - 1);
    // 1. 先实时调用计算排名接口（用params传参）
    await axios.post(`/scholarship/ranking/calculate/${selectedGrade.value}`, null, {
      params: {
        academicYear: academicYear,
        scholarshipType: selectedScholarshipType.value
      }
    });
    // 2. 再查排名
    const response = await axios.get(`/scholarship/ranking/${selectedGrade.value}`, {
      params: {
        academicYear: academicYear,
        scholarshipType: selectedScholarshipType.value
      }
    });
    if (response.data.status === 200) {
      rankingList.value = response.data.data || [];
      if (!silent) ElMessage.success('查询排名成功');
    } else {
      if (!silent) ElMessage.warning('暂无排名数据');
      rankingList.value = [];
    }
  } catch (error) {
    console.error('查询排名失败:', error);
    if (!silent) ElMessage.error('查询失败，请稍后重试');
    rankingList.value = [];
  } finally {
    if (!silent) loading.value = false;
  }
};

const updatingQualification = ref(false);

const updateAllCandidatesQualified = async () => {
  try {
    updatingQualification.value = true;
    const response = await axios.put('/scholarship/candidates/update-all-qualified');
    if (response.data.success) {
      ElMessage.success('所有学生已成功设置为符合条件');
      await loadScholarshipAndCandidateData(); // 重新加载奖学金数据和候选人数据
    } else {
      ElMessage.error(response.data.message || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
  } finally {
    updatingQualification.value = false;
  }
};

// 格式化学年显示
const formatAcademicYear = (year) => {
  if (!year) return '';
  // 如果已经是xxxx-xxxx格式，直接返回
  if (year.includes('-')) return year;
  // 如果是xxxx格式，转换为xxxx-(xxxx+1)格式
  const yearNum = parseInt(year);
  if (!isNaN(yearNum)) {
    return `${yearNum}-${yearNum + 1}`;
  }
  return year;
};

// 统计数据
const rankingPage = ref(1);
const rankingPageSize = ref(10);
const candidatePage = ref(1);
const candidatePageSize = ref(10);

// 分页后的排名列表
const pagedRankingList = computed(() => {
  if (!Array.isArray(rankingList.value)) return [];
  const start = (rankingPage.value - 1) * rankingPageSize.value;
  return rankingList.value.slice(start, start + rankingPageSize.value);
});

// 分页后的候选人列表
const pagedCandidateList = computed(() => {
  if (!Array.isArray(filteredCandidateList.value)) return [];
  const start = (candidatePage.value - 1) * candidatePageSize.value;
  return filteredCandidateList.value.slice(start, start + candidatePageSize.value);
});

const handleRankingPageChange = (page) => {
  rankingPage.value = page;
};
const handleCandidatePageChange = (page) => {
  candidatePage.value = page;
};
</script>

<style scoped>
.main {
  display: flex;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.left {
  width: 250px;
  padding: 20px;
  flex-shrink: 0; /* 防止收缩 */
  min-height: 100vh; /* 确保最小高度 */
}

.right {
  flex: 1;
  padding: 20px;
}

.card-box {
  height: calc(100vh - 40px); /* 固定高度，减去padding */
  position: sticky; /* 粘性定位 */
  top: 20px;
  overflow-y: auto; /* 内容过多时可滚动 */
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  color: #666;
}

.menu-item:hover {
  background-color: #f0f0f0;
  color: #409eff;
}

.menu-item.active {
  background-color: #409eff;
  color: white;
}

.menu-item i {
  margin-right: 10px;
  font-size: 16px;
}

.content {
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.content-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

/* 统计卡片样式 */
.dashboard {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 表格样式 */
.el-table {
  margin-top: 16px;
}

/* 思政成绩样式 */
.political-score {
  margin-top: 20px;
}

.total-score {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
}

/* 通知公告样式 */
.notice-list {
  margin-top: 20px;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main {
    /* 移除 flex-direction: column; 保持水平布局 */
  }

  .left {
    width: 250px; /* 保持固定宽度，不随屏幕大小变化 */
    padding: 10px;
    flex-shrink: 0; /* 防止收缩 */
    min-height: 100vh; /* 确保最小高度 */
  }

  .right {
    padding: 10px;
    flex: 1;
  }

  .card-box {
    height: calc(100vh - 20px); /* 固定高度，减去padding */
    position: sticky; /* 粘性定位 */
    top: 10px;
    overflow-y: auto; /* 内容过多时可滚动 */
  }

  .content {
    padding: 16px;
  }

  .content-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}

/* 表格操作按钮样式 */
.el-table .el-button {
  margin-right: 5px;
}

.el-table .el-button:last-child {
  margin-right: 0;
}

/* 搜索和筛选区域样式 */
.content-header > div {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 奖学金类型标签样式 */
.el-tag--success {
  font-weight: 500;
}

/* 分数显示样式 */
.score-display {
  font-weight: bold;
  color: #409eff;
}

.ranking-display {
  color: #e6a23c;
  font-weight: 500;
}

/* 知识产权模块样式 */
.ip-statistics {
  margin-bottom: 20px;
}

.ip-statistics .stat-card {
  text-align: center;
  transition: transform 0.3s;
}

.ip-statistics .stat-card:hover {
  transform: translateY(-5px);
}

.ip-statistics .stat-content {
  padding: 15px;
}

.ip-statistics .stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.ip-statistics .stat-label {
  font-size: 12px;
  color: #666;
}

/* 知识产权表格样式 */
.ip-list .el-table {
  margin-top: 16px;
}

.ip-list .el-table .el-button {
  margin-right: 5px;
}

.ip-list .el-table .el-button:last-child {
  margin-right: 0;
}

/* 知识产权详情对话框样式 */
.ip-detail-dialog .el-descriptions {
  margin-bottom: 20px;
}

.ip-detail-dialog .el-descriptions-item__label {
  font-weight: bold;
  color: #333;
}

/* 搜索和筛选区域样式 */
.content-header > div {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .content-header > div {
    flex-direction: column;
    align-items: stretch;
  }

  .content-header > div .el-input,
  .content-header > div .el-select,
  .content-header > div .el-button {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
}

.ranking-info {
  margin-bottom: 20px;
}

.ranking-list {
  margin-top: 20px;
}

.candidate-list {
  margin-top: 20px;
}

.ranking-info .el-card {
  border-left: 4px solid #409eff;
}

.ranking-list .el-card {
  border-left: 4px solid #67c23a;
}

.candidate-list .el-card {
  border-left: 4px solid #e6a23c;
}
</style>